<template>
  <div class="box_chat_search">
    <div>
      <fileBut
        style="margin: 10px"
        :fileName="fileData.originalName"
        :filePath="fileData.filePath"
        :type="fileData.fileUploadType"
        @close="deleteFile"
        v-if="fileData.id && (moduleType === 'DOC' || moduleType === 'IMG')"
      ></fileBut>
      <fileBut
        style="margin: 10px"
        :fileLink="inputUtils.fileLink"
        :type="inputUtils.fileUploadType"
        @close="deleteClose"
        v-if="inputUtils.fileLink"
      ></fileBut>
    </div>
    <div style="padding: 10px" v-if="uploadShow && moduleType === 'DOC'">
      <el-upload
        :action="$config.jBaseURL + 'base/file/upload'"
        :on-progress="uploadFile"
        :on-success="handlePreview"
        :before-upload="beforeUpload"
        :disabled="!!inputUtils.fileLink"
        :accept="accept"
        multiple
        :data="{
          createUserId: 1,
        }"
        list-type="none"
      >
        <h-tooltip>
          <div slot="content">
            <div style="margin: 0 5px">文件数量：最多1个</div>
            <br />
            <div style="margin: 0 5px">
              文件类型：.doc,.docx,.ppt,.pptx,.xls,.xlsx,.pdf,.txt,.html,.htm,.md,.epub,.csv,.mobi,.png,.jpg,.jpeg
            </div>
          </div>
          <HButtom :disabled="!!inputUtils.fileLink" round>上传文件</HButtom>
        </h-tooltip>
      </el-upload>
      <HButtom @click="buttonLink" :disabled="!!fileData.id" round
        >文件链接</HButtom
      >
    </div>
    <div style="padding: 10px" v-if="uploadShow && moduleType === 'IMG'">
      <el-upload
        :action="$config.jBaseURL + 'base/file/upload'"
        :on-progress="uploadFile"
        :on-success="handlePreview"
        :before-upload="beforeUpload2"
        :disabled="!!inputUtils.fileLink"
        :accept="accept2"
        multiple
        :data="{
          createUserId: 1,
        }"
        list-type="none"
      >
        <h-tooltip>
          <div slot="content">
            <div style="margin: 0 5px">文件数量：最多1个</div>
            <br />
            <div style="margin: 0 5px">文件类型：.png,.jpg,.jpeg</div>
          </div>
          <HButtom :disabled="!!inputUtils.fileLink" round>上传文件</HButtom>
        </h-tooltip>
      </el-upload>
      <HButtom @click="buttonLink" :disabled="!!fileData.id" round
        >文件链接</HButtom
      >
    </div>
    <div class="box_search_theme">
      <i
        v-if="moduleType === 'DOC' || moduleType === 'IMG'"
        @click="fileUpload"
        class="el-icon-paperclip icon hover"
      ></i>
      <h-input
        v-model="inputText"
        type="textarea"
        ref="inputText"
        @focus="inputFocus"
        @blur="inputBlur"
        id="inputText"
        style="width: 100%; font-size: 16px"
        @keydown.native="handleKeyCode($event)"
        :autosize="{ minRows: 1, maxRows: 8 }"
        placeholder="请输入您想了解的内容，可使用shift+Enter换行"
      ></h-input>

      <div class="submit">
        <h-tooltip content="发送">
          <i
            v-show="!loading"
            @click="submit"
            :class="{ disable: !inputText }"
            class="el-icon-top icon2"
          ></i>
        </h-tooltip>
        <h-tooltip content="终止提问">
          <i
            v-show="loading"
            @click="stop"
            :class="['el-icon-loading', 'icon2', 'disableLoading']"
          ></i>
        </h-tooltip>
      </div>
    </div>
    <!-- 文件链接上传弹窗 -->
    <el-dialog
      title="文件链接"
      append-to-body
      style="margin-top: 30vh"
      :visible.sync="urlShow"
      width="400px"
    >
      <h-input v-model="urlText" placeholder="请输入文件链接"></h-input>
      <span slot="footer" class="dialog-footer">
        <HButtom @click="urlShow = false">取 消</HButtom>
        <HButtom type="primary" @click="submitUrl">确 定</HButtom>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import HButtom from "../utils/HButtom.vue";
import HInput from "../utils/HInput.vue";
import HTooltip from "../utils/HTooltip.vue";
import fileBut from "./fileBut.vue";
import tabs from "./tabs.vue";
import TopBut from "./topBut.vue";
export default {
  components: {
    fileBut,
    TopBut,
    tabs,
    HButtom,
    HInput,
    HTooltip,
  },
  data() {
    return {
      urlShow: false,
      urlText: "",
      inputUtils: {
        fileLink: "",
        fileUploadType: "",
      },
      inputText: "",
      fileData: {},
      uploadShow: false,
      // 文件类型
      accept:
        ".doc,.docx,.ppt,.pptx,.xls,.xlsx,.pdf,.txt,.html,.htm,.md,.epub,.csv,.mobi,.png,.jpg,.jpeg",
      acceptList: [
        "doc",
        "docx",
        "ppt",
        "pptx",
        "xls",
        "xlsx",
        "pdf",
        "txt",
        "html",
        "htm",
        "md",
        "epub",
        "csv",
        "mobi",
        "png",
        "jpg",
        "jpeg",
      ],
      // 文件类型
      accept2: ".png,.jpg,.jpeg",
      acceptList2: ["png", "jpg", "jpeg"],
    };
  },
  computed: {
    // 模块类型
    moduleType() {
      return this.$store.state.aiChat.moduleType;
    },
    // 加载
    loading() {
      return this.$store.state.aiChat.loading;
    },
    // 聊天ai
    contextId() {
      return this.$store.state.aiChat.contextId;
    },
  },
  methods: {
    // 文件上传前的校验 —— 常见的校验有：校验文件类型，文件大小
    beforeUpload(file) {
      // 根据文件名获取文件的后缀名
      let fileType = file.name.split(".").pop().toLowerCase();
      // 判断文件格式是否符合要求
      if (this.acceptList.indexOf(fileType) === -1) {
        this.$message.error("只能上传 " + this.accept + " 格式的文件 !");
        return false;
      }
    },
    // 文件上传前的校验 —— 常见的校验有：校验文件类型，文件大小
    beforeUpload2(file) {
      // 根据文件名获取文件的后缀名
      let fileType = file.name.split(".").pop().toLowerCase();
      // 判断文件格式是否符合要求
      if (this.acceptList2.indexOf(fileType) === -1) {
        this.$message.error("只能上传 " + this.accept2 + " 格式的文件 !");
        return false;
      }
    },
    submitUrl() {
      if (!this.urlText) {
        this.$message.error("请先输入文件链接");
        return;
      }
      if (/^https?:\/\//i.test(this.urlText)) {
        this.inputUtils = {
          fileLink: this.urlText,
          fileUploadType: "LINK",
        };
        this.urlShow = false;
      } else {
        this.$message.error("请输入正确的URL格式");
      }
    },
    buttonLink() {
      this.urlShow = true;
    },
    fileUpload() {
      this.uploadShow = !this.uploadShow;
    },
    stop() {
      this.$store.dispatch("aiChat/stopChat");
    },
    // 获的焦点
    inputFocus() {
      document
        .getElementById("inputText")
        .addEventListener("keydown", this.handleEvent);
    },
    // 失去焦点
    inputBlur() {
      document
        .getElementById("inputText")
        .removeEventListener("keydown", this.handleEvent);
    },
    // ctrl+v 业务处理
    async handleEvent(event) {
      switch (event.keyCode) {
        case 86:
          if (!this.inputUtils.fileLink && !this.fileData.id) {
            let copyContent = await navigator.clipboard.readText();
            if (/^https?:\/\//i.test(copyContent)) {
              // url
              this.inputUtils = {
                fileLink: copyContent,
                fileUploadType: "LINK",
              };
              this.inputText = this.removeChar(this.inputText, copyContent);
            }
          }
          break;
      }
    },
    // 指定删除 字符串
    removeChar(str, char) {
      return str.replace(char, "");
    },
    // 外部触发
    reset() {
      this.uploadShow = false;
      this.deleteFile();
      this.deleteClose();
    },
    // 文件删除
    deleteFile() {
      this.fileData = {
        fileId: "",
        filePath: "",
        fileName: "",
        fileUploadType: "",
      };
    },
    // 链接删除
    deleteClose() {
      this.inputUtils = {
        fileLink: "",
        fileUploadType: "",
      };
    },
    uploadFile() {
      this.$store.commit("aiChat/SET_LOADING", true);
    },
    // 文件添加
    handlePreview(file) {
      this.fileData = {
        ...file.result,
        filePath: file.result.previewPath,
        fileUploadType: "UPLOAD",
      };
      this.$store.commit("aiChat/SET_LOADING", false);
    },
    handleKeyCode(event) {
      if (event.keyCode == 13) {
        if (!event.shiftKey) {
          if (!this.loading) {
            this.submit();
          }
          event.preventDefault();
        }
      }
    },
    // 提交
    submit() {
      if (!this.inputText) return;
      let params = {
        value: this.inputText,
      };
      if (this.moduleType === "DOC" || this.moduleType === "IMG") {
        if (!(this.fileData.id || this.inputUtils.fileLink)) {
          return this.$message.error(`请上传文件或链接进行文档`);
        }
      }
      if (this.fileData.id) {
        params["fileId"] = this.fileData.id;
        params["filePath"] = this.fileData.filePath;
        params["fileName"] = this.fileData.originalName;
        params["fileUploadType"] = this.fileData.fileUploadType;
      } else if (this.inputUtils.fileLink) {
        params["fileLink"] = this.inputUtils.fileLink;
        params["fileUploadType"] = this.inputUtils.fileUploadType;
      }
      this.$emit("submit", params);
      this.inputText = "";
    },
  },
};
</script>

<style lang="scss" scoped>
.box_chat_search {
  background-color: #fff;
  ::v-deep .el-textarea__inner {
    border: 0 !important;
    resize: none !important; /* 这个是去掉 textarea 下面拉伸的那个标志，如下图 */
    font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
      "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
  }
  ::v-deep .el-textarea__inner::placeholder {
    font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
      "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
  }
  margin-bottom: 20px;
  box-shadow: 0px 10px 12px 0px rgba(166, 166, 166, 0.25);
  border-radius: 16px 16px 16px 16px;
  border: 1px solid #e7e7e7;
  .search_file {
    background-color: #f5f5f5;
    margin: 10px;
    border-radius: 10px;
    padding: 10px;
    transition: 0.1s;
    display: flex;
    justify-content: space-between;
    align-items: center;
    &:hover {
      background-color: #f2f2f2;
    }
  }
  .box_search_theme {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    padding: 10px;
    .icon {
      margin-bottom: 5px;
      transform: rotate(-45deg);
      font-size: 22px;
      font-weight: 700;
    }
    .submit {
      flex: 0 0 40px;
      .icon2 {
        margin-left: 10px;
        padding: 6px 6px 5px 5px;
        border-radius: 50%;
        cursor: pointer;
        font-weight: 700;
        color: #fff;
        font-size: 20px;
        background-color: #06f;
        &:hover {
          background-color: rgb(1, 88, 218);
        }
      }
    }
  }
}
.disable {
  background-color: #d9d9d9 !important;
  cursor: no-drop !important;
}

.disableLoading {
  background-color: #d9d9d9 !important;
  cursor: pointer !important;
  &:hover {
    background-color: rgb(1, 88, 218) !important;
  }
}
.disableRed {
  background-color: #f1f1f1 !important;
  color: red !important;
  cursor: pointer;
}
.disakled {
  color: #ccc !important;
  cursor: no-drop !important;
}
::v-deep .el-dialog__body {
  padding: 10px 20px 0;
}
</style>
<style lang="scss">
.box_chat_search {
  .el-upload-list {
    display: none !important;
  }
}
</style>
